import { Module } from 'vuex';
import { CommonResult, ResponseCodeEnum, SysMenu, useHttpClient } from 'pf-component';
import { cacheUtils } from '@/constants/util/cache-utils';
import { RootModule } from '@/store/index';
import { systemApi } from '@/constants/api/system-api';

type AppsModule = { currentAppId: string; apps: any[] };
export const apps: Module<AppsModule, RootModule> = {
  namespaced: true,
  state: {
    currentAppId: cacheUtils.get('currentAppId') || '',
    apps: cacheUtils.get('apps') || []
  },
  getters: {
    allApps: (state: AppsModule, getters): SysMenu[] => {
      return state.apps;
    }
  },
  mutations: {
    INIT_APPS: (state: AppsModule, payload: { apps: any[]; currentAppId?: string }) => {
      if (payload && payload.apps && payload.apps.length) {
        let idx = -1;
        const hasCurrentApp =
          payload.currentAppId &&
          (idx = payload.apps.findIndex(v => v.id === payload.currentAppId)) > -1;
        const currentApp = hasCurrentApp ? payload.apps[idx] : payload.apps[0];
        state.currentAppId = currentApp.id;
        state.apps.splice(0, state.apps.length, ...payload.apps);
        cacheUtils.set('currentAppId', state.currentAppId);
        cacheUtils.set('apps', payload.apps);
      } else {
        state.currentAppId = '';
        state.apps.splice(0, state.apps.length);
        cacheUtils.del('currentAppId');
        cacheUtils.del('apps');
      }
    }
  },
  actions: {
    async initApps({ commit }, payload: { tenId: string; appId: string }) {
      const { tenId, appId } = payload;
      return useHttpClient()
        .general(systemApi.appApi.listByTenId, { tenId })
        .then((res: CommonResult<any[]>) => {
          if (res.code === ResponseCodeEnum.SUCCESS) {
            commit('INIT_APPS', { apps: res.data, currentAppId: appId });
            return true;
          } else {
            commit('INIT_APPS', { apps: [] });
          }
        })
        .catch(err => {
          console.error('根据租户获取apps失败：', err);
          return false;
        });
    }
  },
  modules: {}
};
